from lib.settings import HUOBI_API_URL
import hashlib
import time
import urllib
import urllib.parse
import urllib.request
import json


def send2api(pParams, extra, apikey, secretkey):
    pParams['access_key'] = apikey
    pParams['created'] = int(time.time())
    pParams['sign'] = createSign(pParams, secretkey)
    if(extra):
        for k in extra:
            v = extra.get(k)
            if(v != None):
                pParams[k] = v
    tResult = httpRequest(HUOBI_API_URL['host'], pParams)
    return tResult


def createSign(params, secretkey):
    params['secret_key'] = secretkey
    params = sorted(params.items(), key=lambda d:d[0], reverse=False)
    message = urllib.parse.urlencode(params)
    message=message.encode(encoding='UTF8')
    m = hashlib.md5()
    m.update(message)
    m.digest()
    sig=m.hexdigest()
    return sig


def httpRequest(url, params):
    postdata = urllib.parse.urlencode(params)
    postdata = postdata.encode('utf-8')

    if url == HUOBI_API_URL['depth']:
        fp = urllib.request.urlopen(url, postdata, timeout=1)
    else:
        fp = urllib.request.urlopen(url, postdata, timeout=3)

    if fp.status != 200:
        return False
    else:
        mybytes = fp.read()
        mystr = mybytes.decode("utf8")
        fp.close()
        return json.loads(mystr)
